#include "StdAfx.h"
#include "EditDialog.h"

#include "Utils.h"

LRESULT EditDialog::OnInitDialog(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
    AtlCreateMenuBar(m_hWnd, IDR_EDIT_MENU, SHCMBF_HMENU);   

    memoCtrl.SubclassWindow(GetDlgItem(IDC_RICHINK));

    CFontHandle font = AtlGetDefaultGuiFont();
    memoCtrl.SetFont(font);

    memoCtrl.SetFocus();

    if (FileUtils::FileExists(fileName))
        memoCtrl.Load(fileName, unicode);

    VIEWATTRIBUTES  viewAttr;
    memset(&viewAttr, 0, sizeof(viewAttr));
    viewAttr.mask = VIEWATTRIBUTE_ZOOM;
    viewAttr.uZoom = 100;

    memoCtrl.SetViewAttributes(&viewAttr);

    memoCtrl.SetModify(FALSE);

    return bHandled = FALSE;
}

bool EditDialog::OnClose()
{
    if (FileUtils::FileExists(fileName) || memoCtrl.GetTextLength())
    {
        if (!memoCtrl.Save(fileName, unicode)) {

            // TODO: it's needed to handle saving error properly
            MessageBox(LoadString(IDR_MSG_CANTSAVEMEMO).c_str(), LoadString(IDR_MAINFRAME).c_str(), MB_OK | MB_ICONSTOP);
        }
    }

    return true;
}

void EditDialog::OnSize(UINT, const CSize &size)
{
    CRect rect;
    GetClientRect(&rect);
    memoCtrl.SetWindowPos(NULL, 0, 0, rect.Width(), rect.Height(), SWP_NOZORDER | SWP_NOMOVE | SWP_NOACTIVATE);
}

LRESULT EditDialog::OnContextMenu(int /*idCtrl*/, LPNMHDR pnmh, BOOL& /*bHandled*/)
{
    PNMRGINFO pnmrgi = (PNMRGINFO)pnmh ;
    CMenuHandle menu;
    
    menu.LoadMenu(IDR_EDIT_MENU);
    menu = menu.GetSubMenu(0);

    return menu.TrackPopupMenu( TPM_HORIZONTAL | TPM_VERTICAL, pnmrgi->ptAction.x, pnmrgi->ptAction.y, m_hWnd);
}

LRESULT EditDialog::OnSave(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& bHandled)
{
    memoCtrl.Save(fileName, unicode);
    return bHandled = FALSE;
}

static void EnableMenuItem( CMenuHandle& menu, UINT id, BOOL enabled )
{
    menu.EnableMenuItem( id, enabled ? MF_BYCOMMAND | MF_ENABLED : MF_BYCOMMAND | MF_DISABLED | MF_GRAYED );
}

void EditDialog::OnInitMenuPopup(HMENU hMenu, UINT, BOOL)
{
    if (!memoCtrl.IsWindow())
        return;

    CMenuHandle menu;
    menu.Attach(hMenu);

    EnableMenuItem(menu, ID_EDIT_UNDO, memoCtrl.GetModify() && memoCtrl.CanUndo());
    EnableMenuItem(menu, ID_EDIT_REDO, /*memoCtrl.GetModify() &&*/ memoCtrl.CanRedo());

    IntTuple sel = memoCtrl.GetSelection();
    EnableMenuItem(menu, ID_EDIT_CUT, (sel.first != sel.second));
    EnableMenuItem(menu, ID_EDIT_COPY, (sel.first != sel.second));
    EnableMenuItem(menu, ID_EDIT_PASTE, memoCtrl.CanPaste( CF_TEXT ) | memoCtrl.CanPaste( CF_UNICODETEXT ));

    EnableMenuItem(menu, ID_EDIT_SELECTALL, memoCtrl.GetTextLength());
}
